package io.renren.modules.app.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.renren.common.utils.R;
import io.renren.modules.PCguanli.dao.DriversDatcherDao;
import io.renren.modules.PCguanli.entity.DriversDatcherEntity;
import io.renren.modules.app.form.WxCodeForm;
import io.renren.modules.app.wx.WxAppIdEnum;
import io.renren.modules.app.wx.WxUserInfoUtil;
import io.renren.modules.app.wx.WxUserInfoVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author YuTian
 */
@RestController
@RequestMapping("/app/wx")
public class WxLoginController {

    @Autowired
    private DriversDatcherDao driversDatcherDao;

    @Autowired
    private WxMaService  wxMaService;
    /**
     * 微信登录
     *
     * @param form 微信code
     * @return 返回参数值
     */
    @PostMapping("login")
    public R login(@RequestBody WxCodeForm form) {
        //todo 朱子扬 微信管理后台要添加开发者者服务ip白名单
        //通过微信code获取用户openid，并保存用户信息
        WxUserInfoVo wxUserInfoVo = WxUserInfoUtil.getUserInfo(WxAppIdEnum.TAI_HUA.getAppId(), form.getCode());

        //获取用户是否绑定过
        DriversDatcherEntity datcherEntity = driversDatcherDao.selectOne(new LambdaQueryWrapper<DriversDatcherEntity>()
                .eq(DriversDatcherEntity::getOpenId, wxUserInfoVo.getOpenid())
                .last("limit 1")
        );
        //是否登录过。为false没有登录过就回到注册页面绑定
        Boolean isLogin = datcherEntity != null;
        return R.ok().put("data", wxUserInfoVo).put("isLogin", isLogin);
    }
    /**
     * 获取手机号
     *
     *
     */
    @GetMapping("getPhone")
    public R getPhone(String code) throws WxErrorException {
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(code);

        return R.ok().put("data",phoneNoInfo);
    }
}
